package com.base.cn.platform.os.controller.course.cou.play;

import com.base.cn.platform.os.common.constants.CacheConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.TT.TTServiceUtils;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.course.MaterialType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.LoginForm;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.comment.CourseComment;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyPackageCourse;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecord;
import com.base.cn.platform.os.entity.course.cou.packageCou.PackageCourse;
import com.base.cn.platform.os.entity.course.cou.record.CoursePlayRecord;
import com.base.cn.platform.os.entity.course.material.CouMaterial;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogBiz;
import com.base.cn.platform.os.service.course.cloud.CloudServiceBiz;
import com.base.cn.platform.os.service.course.comment.CourseCommentBiz;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordBiz;
import com.base.cn.platform.os.service.course.cou.packageCou.PackageCourseBiz;
import com.base.cn.platform.os.service.course.cou.record.CoursePlayRecordBiz;
import com.base.cn.platform.os.service.course.count.CouMaterialPlayNumBiz;
import com.base.cn.platform.os.service.exam.record.ExamRecordService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.upload.LoggerGenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.IntStream;

/**
 * 播放课程Controller接口
 *
 * @author s.li
 * @create 2018-05-31-14:45
 */
@RestController
@RequestMapping("/course")
public class PlayCourseController extends BaseController {

    @Autowired
    private CourseBiz courseBiz;
    @Autowired
    private CourseBuyRecordBiz courseBuyRecordBiz;
    @Autowired
    private PackageCourseBiz packageCourseBiz;
    @Autowired
    private CourseCatalogBiz courseCatalogBiz;
    @Autowired
    private CoursePlayRecordBiz coursePlayRecordBiz;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CloudServiceBiz cloudServiceBiz;
    @Autowired
    private CourseCommentBiz courseCommentBiz;
    @Autowired
    private ExamRecordService examRecordService;
    @Autowired
    private CouMaterialPlayNumBiz couMaterialPlayNumBiz;
    @Autowired
    private LoggerGenService loggerGenService;
    @Autowired
    private TTServiceUtils ttServiceUtils;

    /**
     * 强烈不建议在controller 使用
     */
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 获取课程播放页面数据
     * @param userId 用户ID
     * @param packageId 餐ID，普通课程传0
     * @param courseId 被播放的课程ID，如果是套餐则传套餐下的课程ID，如果是普通课程则传课程的ID
     * @return CourseBuyRecord
     */
    @RequestMapping("/getPlayCourseBuyRecord")
    public CourseBuyRecord getPlayCourseBuyRecord(@RequestParam("userId") BigDecimal userId,
                                                  @RequestParam(value = "packageId",required = false,defaultValue = "0") BigDecimal packageId,
                                                  @RequestParam(value = "courseId",required = false,defaultValue = "0") BigDecimal courseId){
        CourseBuyRecord courseBuyRecord  =null;
        if(DataUtil.idIsNotNull(packageId)){//套餐课程
            courseBuyRecord = courseBuyRecordBiz.checkUserBuyCourse(userId,packageId,true,true);
        }else{//普通课程
            courseBuyRecord = courseBuyRecordBiz.checkUserBuyCourse(userId,courseId,true,false);
        }
        if(ObjectUtils.isEmpty(courseBuyRecord)){
            courseBuyRecord = new CourseBuyRecord();
            courseBuyRecord.setStatus(0);
            Course course;
            if(DataUtil.idIsNotNull(packageId)) {//套餐课程
                course = courseBiz.findCourseById(true,packageId,false,false,false);
                if(ObjectUtils.isNotEmpty(course)){
                    List<PackageCourse> packageCourseList = packageCourseBiz.findPackageCourseByPackageId(packageId,true);
                    course.setPackageCourseList(packageCourseList);
                }
            }else{
                course = courseBiz.findCourseById(true,courseId,false,false,false);
            }
            if(ObjectUtils.isNotEmpty(course)){
                courseBuyRecord.setCourseTypeKey(course.getCourseTypeKey());
                courseBuyRecord.setCourse(course);
                courseBuyRecord.setCourseId(course.getId());
            }
        }

        //如果是套餐
        if(courseBuyRecord.getCourse()!=null && courseBuyRecord.getCourse().getCourseTypeKey().equals(CourseType.COURSE_TYPE_PACKAGE.getKey()) && DataUtil.idIsNotNull(packageId)){
            StringBuffer stringBuffer = new StringBuffer();
            if(courseBuyRecord.getStatus().intValue()==1){//已经激活
                List<CourseBuyPackageCourse> courseBuyPackageCourseList = courseBuyRecord.getCourseBuyPackageCourseList();
                if(ObjectUtils.isNotEmpty(courseBuyPackageCourseList)){
                    if(DataUtil.idIsNotNull(courseId)){
                        IntStream.range(0,courseBuyPackageCourseList.size()).forEach(index->{
                            CourseBuyPackageCourse packageCourse = courseBuyPackageCourseList.get(index);
                            if(ObjectUtils.isNotEmpty(packageCourse) && packageCourse.getCourseId().compareTo(courseId)==0){
                                stringBuffer.append(index);
                            }
                        });
                    }else{
                        stringBuffer.append(0);
                    }
                }
            }else{//未激活
                List<PackageCourse> packageCourseList = courseBuyRecord.getCourse().getPackageCourseList();
                if(ObjectUtils.isNotEmpty(packageCourseList)){
                    if(DataUtil.idIsNotNull(courseId)){
                        IntStream.range(0,packageCourseList.size()).forEach(index->{
                            PackageCourse packageCourse = packageCourseList.get(index);
                            if(ObjectUtils.isNotEmpty(packageCourse) && packageCourse.getCourseId().compareTo(courseId)==0){
                                stringBuffer.append(index);
                            }
                        });
                    }else{
                        stringBuffer.append(0);
                    }
                }
            }
            if(stringBuffer.length()>0){//设置套餐默认播放的课程的下标
                courseBuyRecord.setIndex(Integer.parseInt(stringBuffer.toString()));
            }
        }
        return courseBuyRecord;
    }

    /**
     * 验证节点的播放
     * @param buyCourseId 课程或套餐ID（购买的课程ID）
     * @param courseId 课程ID
     * @param prevCatalogId 前一个目录节点ID
     * @param catalogId 目录节点ID
     * @param userId 用户ID
     * @return Map<String,Object>
     */
    @RequestMapping("/checkCourseCatalogPlay")
    public Map<String,Object> checkCourseCatalogPlay(@RequestParam("buyCourseId") BigDecimal buyCourseId,
                                                     @RequestParam("courseId") BigDecimal courseId,
                                                     @RequestParam("prevCatalogId") BigDecimal prevCatalogId,
                                                     @RequestParam("catalogId") BigDecimal catalogId,
                                                     @RequestParam("userId") BigDecimal userId)throws IOException {
        CourseCatalog catalog = courseCatalogBiz.findCourseCatalogById(catalogId,true,false,false,false);
        if(ObjectUtils.isEmpty(catalog)){
            return ResultUtil.ERROR("课程目录节点不存在");
        }
        if(ObjectUtils.isEmpty(catalog.getMaterial())){
            return ResultUtil.ERROR("课程目录未设置播放内容");
        }
        //如果是直播
        if(catalog.getMaterialTypeKey().equals(MaterialType.TYPE_KEY_LIVE.getKey())){
            int liveStatus = catalog.getLivePlayState();
            if(liveStatus==2){
                //是否可以提前进入（单位/分）
                int preEnterTime = catalog.getMaterial().getPreEnterTime();
                //距离开始还有多少时间（毫秒）
                long time = catalog.getLessonStartTime().getTime() - System.currentTimeMillis();
                if(time > (preEnterTime * 60 * 1000)){//距离时间大于提前进入时间，则提示未开始
                    return ResultUtil.ERROR("直播未开始");
                }
            }
        }
        Map<String,Object> entity = new HashMap<>();
        entity.put("audition",false);
        entity.put("play",false);
        entity.put("typeKey",catalog.getMaterialTypeKey());
        // 0 表示正常 1 表示需要购买 2 表示有购买记录但过期了
        entity.put("needBuy",0);
        String message = null;
        //不限制有效期
        CourseBuyRecord courseBuyRecord = courseBuyRecordBiz.checkUserBuyCourseNoValidity(userId,buyCourseId);
        if(ObjectUtils.isEmpty(courseBuyRecord)){//如果课程没有购买记录
            Course buyCourse = courseBiz.findById(buyCourseId);
            if (buyCourse.getValidType()==2&&buyCourse.getDontBuyTime().compareTo(new Date())==-1) {
                entity.put("needBuy", 3);
                message = "此课程已停售";
            }else{
                int audition = catalog.getAudition();
                if(audition==2){//可试听
                    entity.put("audition",true);
                    String sign = getSign(userId,buyCourseId,courseId,catalogId);
                    customCacheChannel.set(J2CacheRegion.ONE_MINUTE_REGION.getKey(), sign, catalog);
                    entity.put("sign",sign);
                }else{
                    entity.put("needBuy",1);
                    message = "还未购买此课程，建议立即购买此课，学习更多章节！";
                }
            }

        }else{
            //有购买记录
            //验证购买的课程是否过期
            if(courseBuyRecord.getValidTime().compareTo(new Date())==-1){
                entity.put("needBuy",2);
                message = "此课程观看有效期已到，请重新购买再次学习！";
                return   ResultUtil.SUCCESS(message,entity);
            }
            int status = courseBuyRecord.getStatus();
            if(status==0){
                return ResultUtil.ERROR("套餐课程未激活，请激活套餐后再学习");
            }
            Course buyCourse;
            //购买的课程数据对象buyCourseId
            if(courseId.compareTo(BigDecimal.ZERO)==0){
                buyCourse = courseBiz.findById(buyCourseId);
            }else {
                buyCourse = courseBiz.findById(courseId);
            }
            //如果有学习限制
            if(buyCourse.isStudyLimited() && !buyCourse.getCourseTypeKey().equals(CourseType.COURSE_TYPE_LIVE.getKey()) && DataUtil.idIsNotNull(prevCatalogId)){
                Map<String,Object> resultMap = this.checkStudyLimit(userId,buyCourse,courseId,prevCatalogId,catalog);
                if(ObjectUtils.isNotEmpty(resultMap)){
                    return resultMap;
                }
            }
            //如果是直播
            if(catalog.getMaterialTypeKey().equals(MaterialType.TYPE_KEY_LIVE.getKey())){
                //1正在播放，2未开始，3已过期
                int liveStatus = catalog.getLivePlayState();
                if(liveStatus==3){//如果直播已结束
                    //回放状态
                    int replay = catalog.getReplay();
                    if(replay==1){//可回放
                        String backCode = catalog.getBackCode();
                        if(StringUtils.isNotEmpty(backCode)){//如果有回放码，则把直播转成录播
                            catalog.setMaterialTypeKey(MaterialType.TYPE_KEY_VIDEO.getKey());
                            catalog.getMaterial().setTypeKey(MaterialType.TYPE_KEY_VIDEO.getKey());
                            catalog.getMaterial().setPlayUrl(backCode.trim());//把回放的码，设置到对象中
                        }else{
                            return ResultUtil.ERROR("直播回放还未生成，请稍后重试");
                        }
                    }else{
                        return ResultUtil.ERROR("直播已结束，且没有设置回放");
                    }
                }
            }
            CoursePlayRecord playRecord = coursePlayRecordBiz.findUserCatalogPlayRecord(userId,buyCourseId,courseId,catalogId);
            catalog.setCoursePlayRecord(playRecord);
            //验证节点是否可以进行评论
            CourseComment condition = new CourseComment();
            condition.setCourseId(courseId);
            condition.setCatalogId(catalogId);
            condition.setUserId(userId);
            List<CourseComment> courseCommentList = courseCommentBiz.findCourseCommentList(condition, false, false, false);
            if (ObjectUtils.isNotEmpty(courseCommentList)) {
                entity.put("isEvaluate",false);
            }else{
                entity.put("isEvaluate",true);
            }
            entity.put("play",true);
            if (ObjectUtils.isNotEmpty(playRecord)) {
                entity.put("duration", playRecord.getDuration());
            }
            String sign = getSign(userId,buyCourseId,courseId,catalogId);
            //缓存一分钟
            customCacheChannel.set(J2CacheRegion.ONE_MINUTE_REGION.getKey(), sign, catalog);
            customCacheChannel.set(J2CacheRegion.ONE_MINUTE_REGION.getKey(), sign+"_userId", userId);
            entity.put("sign",sign);
        }
        return ResultUtil.SUCCESS(message,entity);
    }

    /**
     * 获取播放数据
     * @param request
     * @param sign
     * @param source
     * @param nickname
     * @param userAvatar
     * @param userId
     * @param mobile
     * @return
     */
    @RequestMapping("/loadPlayData")
    public Map<String,Object> loadPlayData(HttpServletRequest request,
                                           @RequestParam("sign") String sign,
                                           @RequestParam("source") String source,
                                           @RequestParam(value = "nickname",required = false) String nickname,
                                           @RequestParam(value = "userAvatar",required = false) String userAvatar,
                                           @RequestParam(value = "userId", required = false) BigDecimal userId,
                                           @RequestParam(value = "mobile", required = false) String mobile){
        CourseCatalog catalog = (CourseCatalog) customCacheChannel.get(J2CacheRegion.ONE_MINUTE_REGION.getKey(), sign).getValue();
        if(ObjectUtils.isEmpty(userId)){
            userId = (BigDecimal) customCacheChannel.get(J2CacheRegion.ONE_MINUTE_REGION.getKey(), sign+"_userId").getValue();
        }
        if(ObjectUtils.isEmpty(catalog)){
            return ResultUtil.ERROR("播放数据失效");
        }
        TreeMap<String, String> config;
        customCacheChannel.evict(J2CacheRegion.ONE_MINUTE_REGION.getKey(),sign);
        Map<String,Object> resultMap = ResultUtil.SUCCESS(catalog);
        if(catalog.getMaterialTypeKey().equals(MaterialType.TYPE_KEY_VIDEO.getKey()) || catalog.getMaterialTypeKey().equals(MaterialType.TYPE_KEY_AUDIO.getKey())){//视频、音频
            CouMaterial material = catalog.getMaterial();
            resultMap.put("isK96keVideo",false);
            TreeMap<String, String> sysConfigContext = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
            if(material.getPlayType().equals("96K") || sysConfigContext.get("isK96keVideo").equals("ON")){
                resultMap.put("isK96keVideo",true);
                config = sysConfigService.getSysConfigContext(ConfigName.V96K);
                if(catalog.getMaterial().getPlayType().equals("CC")&&StringUtils.checkUrl(catalog.getBackCode())){
                    this.dealUrl(catalog, catalog.getBackCode());
                    resultMap.put("player",catalog.getBackCode()+"&autoLogin=true&viewertoken="+catalog.getMaterial().getStudentCode()+"&viewername="+nickname);
                    resultMap.put("isK96keVideo",false);
                    catalog.setMaterialTypeKey(MaterialType.TYPE_KEY_LIVE.getKey());
                    catalog.getMaterial().setTypeKey(MaterialType.TYPE_KEY_LIVE.getKey());
                }else{
                    resultMap.put("player",config.get("player"));
                }
            }
        } else if (catalog.getMaterialTypeKey().equals(MaterialType.TYPE_KEY_LIVE.getKey())) {//直播类型
            CouMaterial material = catalog.getMaterial();
            //直播节录播放状态，1正在播放，2未开始，3已过期
            int liveState = catalog.getLivePlayState();
            int preEnterTime = catalog.getMaterial().getPreEnterTime();
            //距离开始还有多少时间（毫秒）
            long time = catalog.getLessonStartTime().getTime() - System.currentTimeMillis();
            if (!(time > (preEnterTime * 60 * 1000))) {//距离时间大于提前进入时间，则提示未开始
                liveState = 1;
                catalog.setLivePlayState(1);
            }
            if (liveState == 3) {//已结束
                resultMap.put("player", material.getPlayUrl());
            } else if (liveState == 1 || liveState == 2) {//直播中
                if (material.getPlayType().equals("CC")) {
                    config = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
                    if (material.getLiveBilling() == 1) {
                        resultMap.put("player", "https://class.csslcloud.net/index/talker/?roomid=" + material.getPlayUrl() + "&userid=" + config.get("ccAppId") + "&autoLogin=true&username=" + nickname + "&password=" + material.getStudentCode());
                    } else {
                        resultMap.put("player", "https://view.csslcloud.net/api/view/index?roomid=" + material.getPlayUrl() + "&userid=" + config.get("ccAppId") + "&autoLogin=true&viewername=" + nickname + "&viewertoken=" + material.getStudentCode());
                    }
                } else {
                    //如果是小班课验证人数
                    if (StringUtils.isNotEmpty(material.getMaxUsers())) {
                        Integer number = ttServiceUtils.getLiveNumber(material.getRoomId());
                        if (number.intValue() >= Integer.valueOf(material.getMaxUsers()).intValue()) {
                            return ResultUtil.ERROR("该小班课可加入人数已达到设定值");
                        }
                    }
                    Map params = new HashMap();
                    params.put("uuid", userId.toString());
                    params.put("nickName", nickname);
                    params.put("avatar", userAvatar);
                    params.put("classId", material.getRoomId());
                    params.put("role", "3");
                    Map<String, Object> LiveParamMap = ttServiceUtils.getLiveParam(params);
                    if ((boolean) LiveParamMap.get("success")) {
                        Map entityMap = (Map) LiveParamMap.get("entity");
                        if (LoginForm.LOGIN_FROM_MOBILE.equals(source)) {
                            resultMap.put("player", entityMap.get("mRoomUrl").toString());
                        } else if (LoginForm.LOGIN_FROM_PC.equals(source)) {
                            resultMap.put("player", entityMap.get("classRoomUrl").toString());
                        } else if (LoginForm.LOGIN_FORM_APP.equals(source)) {
                            Map tLiveParams = new HashMap();
                            tLiveParams.put("roomId", entityMap.get("classId"));
                            tLiveParams.put("userId", entityMap.get("UID"));
                            tLiveParams.put("safeKey", entityMap.get("safeKey"));
                            tLiveParams.put("timeStamp", entityMap.get("timeStamp"));
                            tLiveParams.put("expiresIn", entityMap.get("expires_in"));
                            catalog.setTLiveParams(tLiveParams);
                        }
                    }
                }
            }
        }
        if(ObjectUtils.isNotEmpty(catalog.getMaterial())&&ObjectUtils.isNotEmpty(catalog.getMaterial().getPlayType())){
            TreeMap<String, String> VLASPROVIDER = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
            TreeMap<String, String> V96K = sysConfigService.getSysConfigContext(ConfigName.V96K);
            if(ObjectUtils.isNotEmpty(catalog.getMaterial().getPlayType())&&catalog.getMaterial().getPlayType().equals("CC")){
                resultMap.put("liveAccount",VLASPROVIDER.get("ccAppId") );
            }
            else if(catalog.getMaterial().getPlayType().equals("96K")){
                resultMap.put("liveAccount",V96K.get("customerKey"));
            }else{
                resultMap.put("liveAccount","");
            }
        }
        //保存播放统计
        couMaterialPlayNumBiz.createMaterialPlayNum(catalog.getId());
        loggerGenService.genSubjectStudUvLog(catalog.getMaterial().getSubjectIds());
        long now = System.currentTimeMillis();
        customCacheChannel.set(J2CacheRegion.ONE_DAY_REGION.getKey(), CacheConstants.LAST_LEARNFLOW_TIME  + userId , now);
        return resultMap;
    }

    /**
     * 验证随堂练习数据
     * @param courseId 购买课程的ID
     * @param catalogId 目录ID
     * @return Map<String,Object>
     */
    @RequestMapping("/checkExercises")
    public Map<String,Object> checkExercises(@RequestParam("userId") BigDecimal userId,
                                             @RequestParam("courseId") BigDecimal courseId,
                                             @RequestParam("catalogId") BigDecimal catalogId){

        CoursePlayRecord coursePlayRecord = coursePlayRecordBiz.findOne("userId="+userId+" and courseId="+courseId +" and catalogId="+catalogId,null);
        if(ObjectUtils.isEmpty(coursePlayRecord)){
            return ResultUtil.ERROR("未学习该章节，不能进行随堂练习");
        }
        if(coursePlayRecord.getFinish().intValue() !=2){
            return ResultUtil.ERROR("该章节未完成学习，不能进行随堂练习");
        }
        CourseCatalog courseCatalog = courseCatalogBiz.findById(catalogId);
        if(ObjectUtils.isEmpty(courseCatalog)){
            return ResultUtil.ERROR("目录不存在，不能进行随堂练习");
        }
        //目录对应的随堂练习的试题ID
        String questionIds = courseCatalog.getQuestionIds();
        if(StringUtils.isEmpty(questionIds)){
            return ResultUtil.ERROR("目录未设置随堂练习试题");
        }
        return examRecordService.createCatalogExam(userId,courseId,catalogId,questionIds,courseCatalog.getCatalogName());
    }

    /**
     * 验证学习限制
     * @param userId 用户ID
     * @param buyCourse 购买的课程对象
     * @param courseId 播放的课程ID
     * @param prevCatalogId 前一个目录节点ID
     * @param catalog 当前要播放的目录节点
     * @return Map<String,Object>
     */
    private Map<String,Object> checkStudyLimit(BigDecimal userId, Course buyCourse,BigDecimal courseId, BigDecimal prevCatalogId, CourseCatalog catalog) {
        //查询已完成学习的前一个节点学习记录
        CoursePlayRecord prevCoursePlayRecord = coursePlayRecordBiz.findOne("userId = "+userId+" and buyCourseId="+buyCourse.getId()+" and courseId="+courseId+" and catalogId="+prevCatalogId+" and finish=2",null);
        CourseCatalog prevCatalog = courseCatalogBiz.findById(prevCatalogId);
        if(ObjectUtils.isEmpty(prevCoursePlayRecord)){//没有学习记录
            return ResultUtil.ERROR("请先完成【"+prevCatalog.getCatalogName()+"】节点的学习");
        }else{//如果有学习记录
            int studyLimit = buyCourse.getStudyLimit();
            //上一个节点，有设置有随堂练习
            if(StringUtils.isNotEmpty(prevCatalog.getQuestionIds()) && studyLimit==3){//考试限制
                //随堂练习总分数
                int practice = prevCatalog.getPractice();
                //用户随堂练习得分
                int _practice = prevCoursePlayRecord.getPractice();
                //课程通过得分率
                double scorePercent = buyCourse.getScorePercent();
                //用户得分率
                double _scorePercent =  new Double(_practice) / new Double(practice) * 100D;
                //如果未通过
                if(scorePercent > _scorePercent){
                    return ResultUtil.ERROR("目录节点【"+prevCatalog.getCatalogName()+"】的随堂练习得分率必须达到【"+scorePercent+"%】以上,才可学习此节！！");
                }
            }
        }
        return null;
    }

    /**
     *   获取签名
     * @param userId 用户ID
     * @param buyCourseId 购买的课程/套餐ID
     * @param courseId 课程ID
     * @param catalogId 目录ID
     * @return 处理后的签名
     */
    private String getSign(BigDecimal userId,BigDecimal buyCourseId,BigDecimal courseId,BigDecimal catalogId){
        String sign = StringUtils.getRandomString(32)+System.currentTimeMillis()+userId+buyCourseId+courseId+catalogId;
        sign = MD5.getMD5(sign).toUpperCase();
        return sign;
    }


    /**
     * 处理直播回放地址，获取url中的参数
     *
     * @param
     */
    private void dealUrl(CourseCatalog courseCatalog, String url) {
        int index = url.indexOf("?");
        String paramsStr = url.substring(index+1);
        String[] paramsArr = paramsStr.split("&");
        for (int i = 0; i < paramsArr.length; i++) {
            String param = paramsArr[i];
            String[] split = param.split("=");
            if (split[0].equals("roomid")) {
                courseCatalog.setRoomid(split[1]);
            } else if (split[0].equals("liveid")) {
                courseCatalog.setLiveId(split[1]);
            }else if (split[0].equals("recordid")){
                courseCatalog.setRecordid(split[1]);
            } else if (split[0].equals("userid")) {
                courseCatalog.setLiveUserId(split[1]);
            }

        }
    }

    /**
     * 查询用户播放最新节点
     * @param userId 用户ID
     * @param buyCourseId 购买的课程ID
     * @param courseId 播放的课程ID
     * @return  CoursePlayRecord
     */
    @RequestMapping("/findUserNewPlayRecord")
    public CoursePlayRecord findUserNewPlayRecord(@RequestParam("userId")BigDecimal userId,
                                                  @RequestParam(value = "buyCourseId",required = false) BigDecimal buyCourseId,
                                                  @RequestParam(value = "courseId",required = false)  BigDecimal courseId){
        return coursePlayRecordBiz.findUserNewPlayRecord(userId,buyCourseId,courseId);
    }
}
